export default {
  data() {
    return {
      _contentBoxTop: 0
    }
  },

  beforeRouteLeave(to, form, next) {
    const scrollTop = this.getEle().scrollTop
    this._contentBoxTop = scrollTop
    this._handleScrollY('get')
    form.meta.keep = false
    next()
  },

  activated() {
    // this.$route.meta.keep  为 true 时 重新获取数据
    const isKeep = this.$route.meta.keep
    if (!isKeep) {
      // 需要缓存数据
      this.getEle().scrollTop = this._contentBoxTop
      this._handleScrollY('set')
    } else {
      this.comReset()
    }
  },

  methods: {
    // 处理Y轴 配合 ZmScrollX 组件使用
    _handleScrollY(key) {
      this._scrollYData = this._scrollYData || {}
      const scrollY = document.getElementsByName('ZMSCROLLX')
      for (let i = scrollY.length; i--; ) {
        if (key === 'get') {
          this._scrollYData[i] = scrollY[i].scrollLeft
        } else if (key === 'set') {
          scrollY[i].scrollLeft = this._scrollYData[i] || 0
        }
      }
    },

    // 兼容 ref 写在组件上
    getEle() {
      const key = 'scrollBox'
      if (!this.$refs[key]) {
        return {}
      }
      return this.$refs[key].$el || this.$refs[key]
    },

    // 可以重写这个方法 刷新数据
    comReset() {
      this.resetData()
      this.init && this.init()
    },

    resetData() {
      Object.assign(this.$data, this.$options.data())
    }
  }
}
